package com.leilei.serviceProject.domain.strategy.service.rule.tree.impl;

import com.leilei.serviceProject.domain.strategy.model.valobj.RaffleResultCheckVo;
import com.leilei.serviceProject.domain.strategy.model.valobj.StrategyAwardCountSurplusVo;
import com.leilei.serviceProject.domain.strategy.repository.IStrategyRepository;
import com.leilei.serviceProject.domain.strategy.service.armory.IStrategyDispatch;
import com.leilei.serviceProject.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.leilei.serviceProject.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yanglei
 * @description 规则树库存节点
 * @create 2024/11/19 17:17
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {
    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeLogicResultEntity logic(Long strategyId, String userId, Integer awardId, String ruleValue) {
        log.info("规则树过滤-库存扣减 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);
        // 扣减库存 扣减成功：发送至延迟队列通过定时任务异步消费 接管。 扣减失败：库存不足 放行。
        Boolean status = strategyDispatch.awardStockDeduction(strategyId, awardId);
        if (status) {
            log.info("规则树过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardCountSurplusVo.builder()
                    .strategyId(strategyId)
                    .awardId(awardId)
                    .build());
            return DefaultTreeFactory.TreeLogicResultEntity.builder()
                    .ruleTreeResultCheck(RaffleResultCheckVo.TAKE_OVER)
                    .treeResultData(DefaultTreeFactory.TreeResultData.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }
        // 库存不足
        log.warn("规则树过滤-库存扣减-告警-库存不足。 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeLogicResultEntity.builder()
                .ruleTreeResultCheck(RaffleResultCheckVo.ALLOW)
                .build();
    }
}
